<?php

namespace app\api\controller;

use think\Controller;
use think\Request;

use app\common\controller\Api;

class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];



    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $category_id = $this->request->request('category_id', '');
        $name = $this->request->request('name', '');
        $status = $this->request->request('status', 1);

        $suggest = $this->request->request('suggest', 0);

        $sort = $this->request->request('sort', 'desc');
        $order = $this->request->request('order', 'weigh');

        $model = model('goods');
        if ($category_id) {
            $model->where('category_id', $category_id);
        }

        if ($name) {
            $model->whereLike('name', '%' . $name . '%');
        }

        if ($status) {
            $model->where('status', $status);

            if ($status == 3) {
                $model->where('goods_starttime', '<', date('Y-m-d H:i:s'), time());
                $model->where('goods_endtime', '>', date('Y-m-d H:i:s'), time());
            }

            //            $h = date('H');
            //
            //            $h = bcdiv($h,1);
            //            if ($status == 3) {
            //                $seckill_id = model('seckill')
            //                ->where('times','<',date('H:m'))
            //                ->where('endtime','>',date('H:m'))
            //                ->order('endtime asc')
            //                ->value('id') ?? 0;
            ////            var_dump($h);
            ////            var_dump($seckill_id);
            //                $model->where('seckill_id',$seckill_id);
            //            }




            //            dump($h);
            //            dump($seckill);

        }

        if ($suggest) {
            // $model->where('suggest', $suggest);
        }

        $list = $model->order($order, $sort)->paginate();

        // foreach ($list as $k => $v) {
        //     if ($v['status'] == 2) {

        //         $list[$k]['price'] = $v['group_price'];
        //     }

        //     if ($v['status'] == 3) {
        //         $list[$k]['start_time'] = strtotime($v['goods_endtime']) - time();
        //         if ($list[$k]['start_time'] < 0) {
        //             $list[$k]['start_time'] = 0;
        //         } else {
        //         }

        //     }
        // }

        $this->success('success', $list);
    }

    public function memberdetail()
    {
        $type = db('memberdetail')->select();
        $list = db('membertype')->where('id','>',0)->select();
        $data['data'] = $type;
        $data['data1'] = $list;
        $this->success('success', $data);
    }

    public function apply(){
        $uid=$this->auth->id;
        $res=model('app\admin\model\Apply')->where('user_id',$uid)->find();
        if($res){
            $this->error("已经申请过了");
        }
        $data['user_id']=$uid;
        $data['createtime']=time();
        model('app\admin\model\Apply')->create($data);
        $this->success('success');
    }
    
    public function category()
    {
        $pid = $this->request->request('pid', 0);
        $type = 'goods';

        $Category = model('Category')
            ->where('type', $type)
            ->where('pid', $pid)
            ->order('weigh desc')
            ->select();

        $this->success('success', $Category);
    }
    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $model = model('goods');
        $goods = $model->where('goods.id', $id)
            ->with(['employ', 'seckill', 'grouporder'])
            ->find();
        if (!$goods) $this->error('商品不存在');
        $goods['start_time'] = 0;
        $goods['end_time'] = 0;
        if ($goods['status'] == 3) {
            $goods['start_time'] = strtotime($goods['goods_endtime']) - time();
            //                $goods['start_time'] = bcmul($goods['start_time'],1000);
            //                $goods['end_time'] = strtotime($goods['goods_endtime']);


        }




        //        $goods['seckill']['endtime'] < date('H:m')

        $employ_ids = $goods['employ_ids'];

        $goods['employ_all'] = model('employ')
            ->whereIn('id', $employ_ids)
            ->select();
        unset($goods['employ']);

        $collect = model('collectgoods')->where('goods_id', $id)
            ->where('user_id', $this->auth->id)
            ->find();
        $goods['is_collect'] = 0;
        if ($collect) {
            $goods['is_collect'] = 1;
        }


        $goods['sku'] = $sku = model('sku')->where('goods_id', $id)->select();

        // if ($goods['status'] == 2) {
        //     $goods['price'] = $goods['group_price'];
        //     foreach ($sku as $k => $v) {
        //         $sku[$k]['price'] = $sku[$k]['money'];
        //     }
        // }


        $goods['comment'] = model('comment')->with('user')->where('goods_id', $id)->limit('2')->select();


        if ($goods['grouporder']) {

            $grouporder = $goods['grouporder'];

            foreach ($grouporder as $k => $v) {

                $groupuser = model('groupuser')->with(['user'])
                    ->where('grouporder_id', $v['id'])
                    ->where('type', 1)
                    ->select();
                if (!$groupuser) {
                    unset($v);
                    continue;
                }
                $grouporder[$k]['groupuser'] = $groupuser;
            }
        }
        $goods['grouptype'] = array_column($goods['sku'], 'name');

        $this->success('success', $goods);
    }

    public function commentList()
    {
        $goods_id = $this->request->request('goods_id', 0);
        $list = model('comment')->with(['user'])->where('goods_id', $goods_id)->paginate();

        $this->success('success', $list);
    }

    public function comment($id)
    {
        $comment = model('comment')->with('user')
            ->where('goods_id', $id)
            ->paginate();
        $this->success('success', $comment);
    }

    public function cart()
    {


        $cart = model('cart')
            ->with(['goods', 'sku'])
            ->where('user_id', $this->auth->id)
            //            ->where('sku_id',$sku_id)
            //            ->where('goods_id',$goods_id)
            ->select();

        $this->success('success', $cart);
    }

    public function deleteCart()
    {
        $ids = $this->request->request('ids', 0);

        model('cart')->where('id', 'in', $ids)->delete();

        $this->success('success');
    }

    public function addCart()
    {
        $goods_id = $this->request->request('goods_id', 0);
        $sku_id = $this->request->request('sku_id', 0);
        $stock = $this->request->request('stock', 0);

        $cart = model('cart')
            ->where('user_id', $this->auth->id)
            ->where('sku_id', $sku_id)
            ->where('goods_id', $goods_id)
            ->find();

        if (!$cart) {
            $data['user_id'] = $this->auth->id;
            $data['sku_id'] = $sku_id;
            $data['goods_id'] = $goods_id;
            $data['stock'] = $stock;
            $data['createtime'] = time();
            model('cart')->save($data);
        } else {
            $cart->stock = bcadd($cart->stock, $stock);
            $cart->save();
        }
        $this->success('success');
    }

    public function editCart()
    {
        $id = $this->request->request('id', 0);

        $stock = $this->request->request('stock', 0);

        if ($stock == 0) {
            model('cart')->where('id', $id)->delete();
        }
        if ($stock > 0) {
            model('cart')->where('id', $id)->update(['stock' => $stock]);
        }

        $this->success('success');
    }



    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    public function goodsCollect()
    {
        $goods_id = $this->request->request('goods_id');
        $collect = model('collectgoods')
            ->where('goods_id', $goods_id)
            ->where('user_id', $this->auth->id)
            ->find();

        if ($collect) {
            $collect->delete();
            $this->success('操作成功');
        }



        $type = model('goods')->where('id', $goods_id)->value('status');

        $inset = [
            'user_id' => $this->auth->id,
            'goods_id' => $goods_id,
            'type' => $type,
            'createtime' => time()
        ];
        model('collectgoods')->insert($inset);
        $this->success('操作成功');
    }

    public function seckillList()
    {
        $list = model('seckill')
            ->where('status', 1)
            ->order('endtime asc')->select();

        $model = model('goods');

        //        endtime

        foreach ($list as $k => $v) {
            //            $list[$k]['type']
            $list[$k]['times_text'] = $list[$k]['times'];
            $list[$k]['endtime_text'] = $list[$k]['endtime'];
            $list[$k]['start_time'] = '';
            $h = date('H');


            if ($list[$k]['times'] > date('H:m')) {
                $list[$k]['type'] = 1;
                $list[$k]['type_text'] = '即将开始';
            } elseif ($list[$k]['times'] < date('H:m') && $list[$k]['endtime'] > date('H:m')) {
                $list[$k]['type'] = 2;
                $list[$k]['type_text'] = '抢购中';

                //                if ($endtime_d<10){
                //                    $endtime_d = '0'.$endtime_d;
                //                }
                $list[$k]['start_time'] = strtotime(date('Y-m-d') . ' ' . $list[$k]['times'] . ':00');
            } else {
                $list[$k]['type'] = 3;
                $list[$k]['type_text'] = '已结束';
            }



            $list[$k]['goods'] = $model->where('seckill_id', $v['id'])->paginate();
        }



        $this->success('success', $list);
    }

    public function couponStatus()
    {
        $goods_id = $this->request->request('goods_id', 0);

        $money = $this->request->request('money', 0);

        $recommend = $this->request->request('recommend', 0);



        //        $this->request->request('goods_id',0);

        $row = model('coupon')
            ->with(['goods'])
            ->where('user_id', $this->auth->id)
            ->where('coupon.status', 1)
            ->find();

        $user = $this->auth->getUser();
        // dump($recommend);
        // dump($user->recommend);
        // exit();



        if (!$row && $recommend > 0 && $goods_id > 0 && $money > 0 && $user->recommend == $recommend) {

            model('app\common\model\Coupon')
                ->where('from_user_id', $recommend)
                ->where('goods_id', $goods_id)
                ->where('status', 'in', '1,2')
                ->update(['status' => 4, 'enttime' => time()]);

            $coupon = [
                'user_id' => $this->auth->id,
                'goods_id' => $goods_id,
                'coupon_sn' => 'CO' . time() . rand(10, 99) . $this->auth->id,
                'discount' => $money,
                'from_user_id' => $recommend,
                'enttime' => strtotime(date('Y-m-d')) + 24 * 60 * 60 * config('site.couponday'),
                'createtime' => time()
            ];

            $coupon_id = model('app\common\model\Coupon')::insertGetId($coupon);


            $row = model('coupon')
                ->with(['goods'])
                ->where('user_id', $this->auth->id)
                ->where('coupon.id', $coupon_id)
                ->find();
        }

        $this->success('success', $row);
    }

    public function acceptCoupon()
    {
        $coupon_id = $this->request->request('coupon_id', 0);




        $coupon = model('coupon')
            ->where('id', $coupon_id)
            ->where('status', 1)
            ->where('user_id', $this->auth->id)
            ->find();

        // if (!$coupon) {

        //     model('app\common\model\Coupon')
        //         ->where('from_user_id',$recommend)
        //         ->where('goods_id',$goods_id)
        //         ->where('status',1)
        //         ->update(['status'=>4]);

        //     model('app\common\model\Coupon')::create([
        //             'user_id'=>$this->auth->id,
        //             'goods_id'=>$goods_id,
        //             'coupon_sn'=>'CO'.time().rand(10,99).$this->auth->id,
        //             'discount'=>$money,
        //             'from_user_id'=>$recommend,
        //         ]);
        // }



        if (!$coupon) $this->error('优惠券不存在');

        $coupon->status = 2;

        $coupon->save();

        $this->success('success');
    }

    //检查可用优惠券

    public function useCoupon()
    {

        $goods_id = $this->request->request('goods_id', 0);

        $coupon = model('coupon')
            ->where('goods_id', $goods_id)
            ->where('status', 2)
            ->where('user_id', $this->auth->id)
            ->find();

        $this->success('success', $coupon);
    }



//获得已经买过的试用装商品ID

    /**
     * 获得已经买过的试用装商品ID
     * @return array|false(返回已经购买的试用装商品IDS)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsVerification()
    {
//        sql
        $order_sql=model('app\common\model\Order');

        $row = $order_sql
            ->with(['ordergoods'])
            ->where('id',$this->auth->id)
            ->where('tpye',3)
            ->whereIn('status',[1,2,3,4,6,8])
            ->select();
//        $this->error($row);
        if (empty($row)){
            return 0;
        }
        $status=[];
        foreach ($row as $k => $v){
            $status=array_merge($status,array_column($v['ordergoods'],'id'));
        }
        return $status;
    }


    //商品列表

    /**
     * 商品列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList()
    {
        $text=$this->request->request('text');
        $category_id=$this->request->request('category_id');
        $goods_ids=$this->request->request('goods_ids/a',[]);
        foreach ($goods_ids as $k=>$v){if (empty($v)) unset($goods_ids[$k]);}
        $goods_s=model('app\admin\model\Goods')
            ->where(function ($query) use ($text, $category_id, $goods_ids) {
                if (!empty($text)) {
                    $query->where('name', 'like', '%' . $text . '%')
                    ->whereOr('content', 'like', '%' . $text . '%');
                }
                if (!empty($category_id)) {
                    $query->where('category_id', $category_id);
                }
                if (!empty($goods_ids) && count($goods_ids) > 0) {
                    $query->whereIn('id', $goods_ids);
                }
            })->select();
        if (empty($goods_s)) {
            $this->error('未查询到商品列表!');
        }else{
            $this->success('success', $goods_s);
        }
    }









}
